package v1

import (
	"fmt"
	"gohub/app/models/role"
	"gohub/app/models/roleperms"
	"gohub/pkg/response"

	"github.com/gin-gonic/gin"
)

type RoleController struct {
	BaseAPIController
}

func (ctrl *RoleController) Index(c *gin.Context) {
	data := role.All()
	response.Data(c, data)
}

// 角色权限
func (ctrl *RoleController) RolePerms(c *gin.Context) {
	data := roleperms.Get(c.Param("id"))
	response.Data(c, data.Data)
}

type rolePerms struct {
	RoleId      string        `json:"roleId"`
	Permissions []interface{} `json:"permissions"`
}

// 角色权限
func (ctrl *RoleController) SetRolePerms(c *gin.Context) {
	var rolePerms rolePerms
	if err := c.BindJSON(&rolePerms); err != nil {
		response.BadRequest(c, err)
		return
	}

	if rolePerms.RoleId == "1" {
		response.Fail(c, "[超级管理员、管理员]角色不能被修改！")
		return
	}

	// 验证 url 参数 id 是否正确
	rolrPermsModel := roleperms.Get(rolePerms.RoleId)
	if rolrPermsModel.ID == 0 {
		response.Abort404(c)
		return
	}

	// 处理权限数据统一格式
	permissions, err := parsePermissions(rolePerms.Permissions)
	if err != nil {
		response.Fail(c, "权限格式错误！")
		return
	}

	rolrPermsModel.Data = permissions
	rowsAffected := rolrPermsModel.Save()
	if rowsAffected > 0 {
		response.Success(c)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

// 解析混合类型的权限数组
func parsePermissions(input []interface{}) ([]string, error) {
	var permissions []string
	for _, item := range input {
		switch v := item.(type) {
		case string:
			permissions = append(permissions, v)
		case float64: // JSON数字默认转为float64
			permissions = append(permissions, fmt.Sprintf("%.0f", v))
		default:
			return nil, fmt.Errorf("无效的权限类型: %T", v)
		}
	}
	return permissions, nil
}
